// components/classic/music/index.js

import {classicBeh} from '../classic-beh.js';

const mMgr = wx.getBackgroundAudioManager()

Component({
  /**
   * 组件的属性列表
   */
  behaviors: [classicBeh],
  properties: {
    musicSrc: String,
    musicTitle: String
  },

  /**
   * 组件的初始数据
   */
  data: {
    playStatus: false,
    playSrc: './images/player@playing.png',
    pauseSrc: './images/player@waitting.png'
  },

  attached: function (argument) {
    /* body... */
    this._recoverStatus()
    this._monitorSwitch()
  },

  /**
   * 组件的方法列表
   */
  methods: {
    onPlay: function () {
      /* body... */
      if (!this.data.playStatus) {
        this.setData({
          playStatus: true
        })
        mMgr.title = this.properties.musicTitle
        mMgr.src = this.properties.musicSrc
      } else { 
        this.setData({
          playStatus: false
        })
        mMgr.pause()
      }
    },
    _recoverStatus: function () {
      /* body... */
      if(mMgr.paused){
        this.setData({
          playStatus: false
        })
      } else if (mMgr.src == this.properties.musicSrc) {
        this.setData({
          playStatus: true
        })
      }
    },

    _monitorSwitch: function () {
      /* 监听背景音频播放事件... */
      mMgr.onPlay(()=>{
        this._recoverStatus()
      })
      /* 监听背景音频暂停事件... */
      mMgr.onPause(()=>{
        this._recoverStatus()
      })
      /* 监听背景音频停止事件... */
      mMgr.onStop(()=>{
        this._recoverStatus()
      })
      /* 监听背景音频自然播放结束事件... */
      mMgr.onEnded(()=>{
        this._recoverStatus()
      })
    }
  }
})
